package com.travelSpring.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.travelSpring.pojo.entity.User;
import com.travelSpring.exception.UserException;
import com.travelSpring.mapper.UserMapper;
import com.travelSpring.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**功能：
*作者：卷心菜
*日期：2025/3/1 18:51
*/
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public List<User> selectAll(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 检查user对象是否所有字段均为null/空
        if (!BeanUtil.isEmpty(user)) {
            // 将非空字段转为查询条件
            Map<String, Object> userMap = BeanUtil.beanToMap(user, false, true);
            queryWrapper.allEq(userMap);
        }
        // 如果user为null或所有字段为空，则查询全部

        return userMapper.selectList(queryWrapper);
    }


    public IPage<User> selectPage(Integer pageSize, Integer pageNum, User user) {
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        // 动态条件
        if (user != null) {
            if (StringUtils.isNotBlank(user.getUsername())) {
                lqw.like(User::getUsername, user.getUsername());
            }
            if (StringUtils.isNotBlank(user.getName())) {
                lqw.like(User::getName, user.getName());
            }
            if (StringUtils.isNotBlank(user.getPhone())) {
                lqw.like(User::getPhone, user.getPhone());
            }
            // 其他条件...
        }
        if (!BeanUtil.isEmpty(user)) {
            // 2. 精确匹配ID（非空时生效）
            lqw.eq(user.getId() != null, User::getId, user.getId());
            // 3. 模糊查询name（非空字符串时生效）
            lqw.like(StrUtil.isNotBlank(user.getName()), User::getName, user.getName());
        }
        // 如果user为null或所有字段为空，则查询全部
        lqw.orderByDesc(User::getId);
        return userMapper.selectPage(page, lqw);
    }
    @Transactional
    public User selectById(String userId) {

        return userMapper.selectById(userId);
    }
    public User login(User user) {
        //验证账户是否存在
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,user.getUsername());
        User dbUser = userMapper.selectOne(lqw);
        if(dbUser == null) {
            throw new UserException("账号不存在,请先登陆");
        }
        //验证密码是否正确
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(user.getPassword(), dbUser.getPassword())) {
            throw new UserException("账号或密码错误");
        }
        String token = TokenUtils.createToken(dbUser.getId() + "-" + dbUser.getRole().toUpperCase(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    public void register(User user) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,user.getUsername());
        User dbUser = userMapper.selectOne(lqw);
        if(dbUser != null) {
            throw new UserException("账户已存在");
        }
        String encodePassword=new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(encodePassword);
        userMapper.insert(user);
    }

    public void add(User user) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,user.getUsername());
        User dbUser = userMapper.selectOne(lqw);
//        if(dbUser != null) {
//            throw new UserException("账户存在");
//        }
        if(StrUtil.isBlank(user.getPassword())) {
            user.setPassword("admin");
        }
        userMapper.insert(user);
    }

    public void update(User user) {
        userMapper.updateById(user);
    }

    @Transactional
    public void updateBatch(List<User> list) {
        for (User user : list) {
            this.update(user);
        }
    }

    public void deleteById(Integer id) {
//        User currentUSer = TokenUtils.getCurrentUser();
//        if(id.equals(currentUSer.getId())) {
//            throw new UserException("不能删除自己");
//        }
        userMapper.deleteById(id);

    }

    @Transactional
    public void deleteBatch(List<User> list) {
//        User currentUser = TokenUtils.getCurrentUser();
//
//        if (list.stream().anyMatch(user -> user.getId().equals(currentUser.getId()))) {
//            throw new UserException("不能删除当前登录账号");
//        }

        List<Integer> ids = list.stream()
                .filter(Objects::nonNull)
                .map(User::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        if (ids.isEmpty()) {
            throw new UserException("未提供有效用户ID");
        }
        userMapper.deleteBatchIds(ids);
    }

    public List<User> selectBatchId(String ids) {
        String[] idArray = ids.split(",");
        return userMapper.selectBatchIds(Arrays.asList(idArray));
    }

    public List<User>selectList() {
        return userMapper.selectList(null);
    }


}
